package com.siruier.boss.ad.widget

import android.animation.*
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.text.TextUtils
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.animation.LinearInterpolator
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import com.qq.e.ads.nativ.NativeUnifiedADData
import com.qq.e.comm.constants.AdPatternType
import com.siruier.boss.R
import com.siruier.boss.databinding.LayoutNativeUnifiedAdInfoBinding
import com.siruier.boss.ui.ext.dp
import com.siruier.boss.ui.utils.GlideUtils

class NativeADUnifiedAdInfoView : ConstraintLayout {
    private lateinit var vb: LayoutNativeUnifiedAdInfoBinding
    private var mAnimatorSet: AnimatorSet? = null
    private var mEndAnimator: ValueAnimator? = null
    private var isVideo: Boolean? = null

    constructor(context: Context) : super(context) {
        initView(context)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        initView(context)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        initView(context)
    }

    private fun initView(context: Context) {
        vb = LayoutNativeUnifiedAdInfoBinding.inflate(LayoutInflater.from(context), this)
        resetUI()
    }

    val clickableViews: List<View?>
        get() {
            val views: MutableList<View?> = ArrayList()
            views.add(vb.imgLogo)
            views.add(vb.imgLogoDownload)
            views.add(vb.btnDownload)
            return views
        }

    fun setAdInfo(ad: NativeUnifiedADData) {
        if (!TextUtils.isEmpty(ad.iconUrl)) {
            GlideUtils.intoView(context, ad.iconUrl, vb.imgLogo)
        }
        vb.textTitle.text = ad.title
        vb.textDesc.text = ad.desc
        isVideo = ad.adPatternType == AdPatternType.NATIVE_VIDEO
    }

    fun updateAdAction(ad: NativeUnifiedADData) {
        // 更新 Ad 文案侧图标
        updateAdButtonIcon(ad)
    }

    fun resetUI() {
        hideProgressBar()
        vb.btnDownload.setCardBackgroundColor(Color.parseColor("#19ffffff"))
        vb.btnDownload.visibility = GONE
        vb.btnDownloadText.visibility = GONE
        vb.textTitle.translationY = 0f
        vb.textDesc.translationY = 0f
    }

    fun playAnim() {
        // 视频播放第4秒 or 图片出现后
        // 文案组：上移94px，离底238px，300ms
        // 按钮背景：出现，#FFFFFF，透明度0%-10%，300ms
        // 按钮图标&文字：出现，透明度从0%-100%，300ms
        // 2s后
        // 按钮背景颜色：从 #FFFFFF-10% 变为 #3185FC，300ms
        if (mAnimatorSet == null) {
            val yValue: Int = 42.dp
            val titleAnim = ObjectAnimator.ofFloat(vb.textTitle, "translationY", 0f, -yValue.toFloat()).setDuration(300)
            val descAnim = ObjectAnimator.ofFloat(vb.textDesc, "translationY", 0f, -yValue.toFloat()).setDuration(300)
            val buttonBGAnim = ObjectAnimator.ofFloat(vb.btnDownload, "alpha", 0f, 1f).setDuration(300)
            val buttonTextAnim = ObjectAnimator.ofFloat(vb.btnDownloadText, "alpha", 0f, 1f).setDuration(300)
            mAnimatorSet = AnimatorSet()
            mAnimatorSet?.addListener(object : Animator.AnimatorListener {
                override fun onAnimationStart(animation: Animator) {}
                override fun onAnimationEnd(animation: Animator) {
                    vb.btnDownload.visibility = VISIBLE
                    vb.btnDownloadText.visibility = VISIBLE
                    if (mEndAnimator == null) {
                        mEndAnimator = ObjectAnimator.ofInt(
                            vb.btnDownload, "cardBackgroundColor",
                            Color.parseColor("#19ffffff"),
                            Color.parseColor("#3185FC")
                        ).setDuration(300)
                        mEndAnimator?.setEvaluator(ArgbEvaluator())
                        mEndAnimator?.startDelay = 1700
                    }
                    mEndAnimator?.start()
                }

                override fun onAnimationCancel(animation: Animator) {}
                override fun onAnimationRepeat(animation: Animator) {}
            })
            mAnimatorSet?.let {
                it.interpolator = LinearInterpolator()
                it.play(titleAnim).with(descAnim).with(buttonBGAnim).with(buttonTextAnim)
            }
        }
        if (isVideo != null && isVideo == true) {
            mAnimatorSet?.startDelay = 4000
            showProgressBar()
        } else {
            mAnimatorSet?.startDelay = 0
        }
        mAnimatorSet?.start()
    }

    private fun pauseAnim() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (mAnimatorSet?.isStarted == true) {
                mAnimatorSet?.pause()
            }
            if (mEndAnimator?.isStarted == true) {
                mEndAnimator?.pause()
            }
        }
    }

    private fun resumeAnim() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (mAnimatorSet?.isPaused == true) {
                mAnimatorSet?.resume()
            }
            if (mEndAnimator?.isPaused == true) {
                mEndAnimator?.resume()
            }
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        pauseAnim()
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        if (isVideo == null) return
        if (isVideo == true) {
            resumeAnim()
        } else {
            // 图文动画比较短，每次显示在屏幕上时，重新播放一次
            resetUI()
            playAnim()
        }
    }

    private fun updateAdButtonIcon(ad: NativeUnifiedADData) {
        if (ad.isWeChatCanvasAd || !ad.isAppAd) {
            vb.imgLogoDownload.setImageResource(R.mipmap.icon_link)
            vb.btnDownloadText.setCompoundDrawablesWithIntrinsicBounds(
                ContextCompat.getDrawable(context, R.mipmap.icon_to_link), null, null, null
            )
            return
        }
        vb.imgLogoDownload.setImageResource(R.mipmap.icon_download_gray)
        vb.btnDownloadText.setCompoundDrawablesWithIntrinsicBounds(
            ContextCompat.getDrawable(context, R.mipmap.icon_download_gray), null, null, null
        )
    }

    private fun showProgressBar() {
        // 留出2dp的间距显示progressbar
        // progressbar的高度为2dp，且在下一视图层级
        // 视频需要显示progressbar，图文不需要
        setPadding(0, 0, 0, 2.dp)
    }

    private fun hideProgressBar() {
        setPadding(0, 0, 0, 0)
    }
}